import React, { useState, useEffect } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
  DialogDescription,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { ScrollArea } from "@/components/ui/scroll-area";
import { QualityIssueTemplateAPI } from "@/api/QualityIssueTemplate";
import { Check } from "lucide-react";

const QualityIssueImportModal = ({ open, onOpenChange, onImport }) => {
  const [templates, setTemplates] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [selectedTemplateIds, setSelectedTemplateIds] = useState(new Set());

  // 打开时加载模板列表
  useEffect(() => {
    if (open) {
      setIsLoading(true);
      QualityIssueTemplateAPI.getList()
        .then((res) => {
          const processedData = res.data.map((t) => ({
            ...t,
            id: t.id || `temp-${Math.random().toString(36).substring(2, 11)}`,
          }));
          setTemplates(processedData);
        })
        .catch((err) =>
          console.error("Failed to load quality issue templates", err)
        )
        .finally(() => setIsLoading(false));
    }
  }, [open]);

  // 切换模板选择状态
  const handleToggleSelection = (id) => {
    setSelectedTemplateIds((prev) => {
      const newSet = new Set(prev);
      newSet.has(id) ? newSet.delete(id) : newSet.add(id);
      return newSet;
    });
  };

  // 确认导入选中的模板
  const handleConfirmImport = () => {
    const selectedTemplates = templates.filter((t) =>
      selectedTemplateIds.has(t.id)
    );
    onImport(selectedTemplates);
    onOpenChange(false);
    setSelectedTemplateIds(new Set());
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[600px]">
        <DialogHeader>
          <DialogTitle>从知识库导入质量通病防治措施</DialogTitle>
          <DialogDescription>
            选择一个或多个质量通病防治措施模板添加到方案中。
          </DialogDescription>
        </DialogHeader>
        <div className="py-4">
          {isLoading ? (
            <p>加载中...</p>
          ) : (
            <ScrollArea className="h-[400px] border rounded-md p-4">
              <div className="space-y-4">
                {templates.length === 0 ? (
                  <p className="text-center text-gray-500">暂无可用模板。</p>
                ) : (
                  templates.map((template) => (
                    <div
                      key={template.id}
                      className="flex items-start gap-4 p-2 rounded-lg hover:bg-gray-50"
                    >
                      <Checkbox
                        id={`template-${template.id}`}
                        checked={selectedTemplateIds.has(template.id)}
                        onCheckedChange={() => handleToggleSelection(template.id)}
                      />
                      <label
                        htmlFor={`template-${template.id}`}
                        className="flex-1 cursor-pointer"
                      >
                        <p className="font-semibold text-gray-800">{template.issueName}</p>
                        <p className="text-sm text-gray-600">分类: {template.category}</p>
                        <p className="text-xs text-gray-500 mt-1">
                          防治措施:{" "}
                          {template.preventionMeasures?.slice(0, 2).join("; ")}
                          {template.preventionMeasures?.length > 2 && "..."}
                        </p>
                      </label>
                    </div>
                  ))
                )}
              </div>
            </ScrollArea>
          )}
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            取消
          </Button>
          <Button
            onClick={handleConfirmImport}
            disabled={selectedTemplateIds.size === 0}
          >
            <Check className="w-4 h-4 mr-2" />
            导入 ({selectedTemplateIds.size})
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};

export default QualityIssueImportModal;